<?php

/**
 * descript:
 * User: blue
 * Date: 2018/9/13 16:51
 */

namespace app\library\server;

use app\library\except\TokenException;
use rabbit\base\Security;
use think\Exception;
use think\facade\Config;
use think\facade\Request;

class TokenS
{
    /**
     * 生成token随机字符串
     * @return string
     */
    public static function makeTokenStr(){
        //token生成规则 md5(随机数+salt+时间戳)
        $str=Security::makeRandon();
        $salt=Config::get('security.token_salt');
        $timestap=$_SERVER['REQUEST_TIME'];
        $token=md5($str.$salt.$timestap);
        return $token;
    }

    /**
     * token 写入缓存
     * @param $token
     * @param array $data
     * @return bool
     */
    public static function TokenToCache($token,$data){
        if(empty($data)) return false;
        $data=json_encode($data);
        $expire=config('security.token_expire');
        $cache=cache($token,$data,$expire);
        if(!$cache) throw new Exception('服务器存入缓存错误');
        return true;
    }

    /**利用token获取响应用户数据
     * @param $key 获取指定字段的用户数据
     * @param bool $all 如果为真,则获取全部数据
     * @return mixed
     */
    public static function getTokenFromCache($key,$all=false){
        $token=Request::header('token');
        $info=cache($token);
        if(!$info) throw new TokenException();
        $infoArr=json_decode($info,true);
        if($all) return $infoArr;
        if(!array_key_exists($key,$infoArr)) {
            throw new Exception('指定键值不存在');
        }else{
            return $infoArr[$key];
        }
    }

    /**判断token是否存在
     * @param $tokn
     */
    public static function tokenVerify(){
        $token=Request::header('token');
        $tokenInfo=cache($token);
        if($tokenInfo){
            // $tokenArr=json_encode($tokenInfo,true);
            if(empty($tokenInfo)) throw new TokenException();
            //更新token有效期
            return $tokenInfo;
        }else{
            throw new TokenException('token无效或者已过期');
        }
    }


}